package com.sui.bigdata.rtcadmin.util;

import com.sui.bigdata.rtcadmin.constant.AppConstant;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: TingWuHuang
 * @Date: 2020/7/2 10:57
 * @description
 */
public class HdfsUtils {
    static Logger logger = LoggerFactory.getLogger(HdfsUtils.class);

    public static void deleteFile(String fileName) throws IOException {
        String hdfsUrl = AppConstant.HDFS_MASTER_URL;
        FileSystem fileSystem = getFileSystem();
        String path = hdfsUrl + fileName;
        if (fileExists(path)) {
            fileSystem.delete(new Path(path), false);
        }
    }

    public static String uploadFileByStream(String fileName, InputStream stream) throws IOException {
        String hdfsUrl = AppConstant.HDFS_MASTER_URL;
        String path = hdfsUrl + fileName;
        uploadModel(path,stream);
        return path;
    }

    public static void uploadModel(String uri, InputStream item) throws IOException {
        FileSystem fileSystem = getFileSystem();
        FSDataOutputStream out = fileSystem.create(new Path(uri));
        IOUtils.copyBytes(item, out, 4096, false);
        out.close();
    }

    public static Boolean fileExists(String path) {
        Boolean res = false;

        try {
            FileSystem fileSystem = getFileSystem();
            res = fileSystem.exists(new Path(path));
        } catch (IllegalArgumentException var3) {
            logger.error("fileExists Exception: ", var3);
        } catch (IOException var4) {
            logger.error("fileExists Exception: ", var4);
        }

        return res;
    }

    private static FileSystem getFileSystem() {
        FileSystem fs = null;
        try {
            fs = FileSystem.get(getHaConfiguration());
        } catch (IOException var2) {
            logger.error("getFileSystem Exception: ", var2);
        }

        return fs;
    }
    public static Configuration getHaConfiguration() {
        Configuration configuration = new Configuration();
        configuration.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        return configuration;
    }
}
